package org.apache.nifi.processors.huawei.abstractprocessor;

import com.huaweicloud.sdk.dli.v1.*;

import org.apache.nifi.annotation.lifecycle.OnScheduled;
import org.apache.nifi.components.ConfigVerificationResult;
import org.apache.nifi.logging.ComponentLog;
import org.apache.nifi.processor.ProcessContext;
import org.apache.nifi.processor.ProcessSession;
import org.apache.nifi.processor.ProcessSessionFactory;
import org.apache.nifi.processor.VerifiableProcessor;
import org.apache.nifi.processor.exception.ProcessException;
import org.apache.nifi.processors.huawei.dli.DLIUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public abstract class AbstractDLIProcessor extends AbstractHuaweiProcessor implements VerifiableProcessor {

    protected volatile DliClient dliClient;

    @OnScheduled
    public void onScheduled(final ProcessContext context) {

        dliClient = DLIUtils.createClient(context);
    }

    @Override
    public List<ConfigVerificationResult> verify(ProcessContext context, ComponentLog verificationLogger, Map<String, String> attributes) {

        final List<ConfigVerificationResult> results = new ArrayList<>();

        try {

            results.add(new ConfigVerificationResult.Builder()
                    .outcome(ConfigVerificationResult.Outcome.SUCCESSFUL)
                    .verificationStepName("Create Client and Configure Region")
                    .explanation("Successfully created DLI Client and configured Region")
                    .build());

        } catch (final Exception e) {

            verificationLogger.error("Failed to create DLI Client", e);
            results.add(new ConfigVerificationResult.Builder()
                    .outcome(ConfigVerificationResult.Outcome.FAILED)
                    .verificationStepName("Create Client and Configure Region")
                    .explanation("Failed to crete DLI Client or configure Region: " + e.getMessage())
                    .build());
        }

        return results;
    }

    /*
     * Allow optional override of onTrigger with the ProcessSessionFactory where required for huawei processors
     *
     * @see AbstractProcessor
     */
    @Override
    public void onTrigger(final ProcessContext context, final ProcessSessionFactory sessionFactory) throws ProcessException {
        final ProcessSession session = sessionFactory.createSession();
        try {
            onTrigger(context, session);
            session.commitAsync();
        } catch (final Throwable t) {
            session.rollback(true);
            throw t;
        }
    }

    /*
     * Default to requiring the "standard" onTrigger with a single ProcessSession
     */
    public abstract void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException;
}
